import json
from json.decoder import WHITESPACE
from logger import log
import time

A_KIND_OF_WEBSOCKET_MAGIC = b"258EAFA5-E914-47DA-95CA-C5AB0DC85B11"

def iterload(string_or_fp, cls=json.JSONDecoder, **kwargs):
	if isinstance(string_or_fp, file):
		string = string_or_fp.read()
	else:
		string = str(string_or_fp)

	decoder = cls(**kwargs)
	idx = WHITESPACE.match(string, 0).end()
	while idx < len(string):
		obj, end = decoder.raw_decode(string, idx)
		yield obj
		idx = WHITESPACE.match(string, end).end()

class Packet(object):
	def __init__(self, data, id = None):
		object.__init__(self)
		self.content = None
		self.valid = False
		self.id = id
		self.time = time.time()

		if type(data) is str:
			try:
				data = json.loads(data)
				self.content = data
				self.valid = True
			except:
				pass
		elif type(data) is dict:
			self.content = data
			self.valid = True

	def isValid(self):
		return self.valid

	def set(self, key, value):
		self.content[key] = value;

	def __getattr__(self, key):
		if ((type(self.content) is dict) and (key in self.content.keys())) or ((type(self.content) is list) and (key in self.content)):
			return self.content[key]
#		elif key == 'a':
#			return None
		else:
			log('Key "%s" not found in Packet'%key)
			return None

	'''def dump(self, name, el, depth = 0):
		result = ''
		if type(el) is dict:
			result += (' '*8*depth)+'%s = {\n'%name
			for k, v in el.items():
				result += self.dump(k, v, depth+1)
			result += (' '*8*depth)+'}\n'
		elif type(el) is list:
			result += (' '*8*depth)+'%s = [\n'%name
			i = 0
			for v in el:
				result += self.dump(None, v, depth+1)
				i += 1
			result += (' '*8*depth)+']\n'
		else:
			if name == None:
				result += (' '*8*depth)+'%s\n'%(el)
			else:
				result += (' '*8*depth)+'%s = %s\n'%(name, el)
		return result'''

	def dump(self, el):
		return json.dumps(self.content)#, separators=(', ', ':'))

	def __str__(self):
		return self.toString()

	def toString(self):
#		return self.dump('@', self.content)
		return self.dump(self.content)

	def toJSON(self):
		return json.dumps(self.content)

	def id(self):
		return id

a = Packet({"a":"b","c":"d","e":{"1":"2","3":["a","b","c"]}})
#print a

#class Socket:
#	def __init__(self):
